// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RouteHandler.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   The router handler
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Routing
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    /// <summary>
    /// The router handler
    /// </summary>
    /// <typeparam name="THttpHandler">The type of the HTTP handler.</typeparam>
    public class RouteHandler<THttpHandler> : MvcRouteHandler
        where THttpHandler : MvcHandler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RouteHandler&lt;THttpHandler&gt;"/> class.
        /// </summary>
        /// <param name="controllerFactory">The controller factory.</param>
        public RouteHandler(IControllerFactory controllerFactory)
            : base(controllerFactory)
        {
        }

        /// <summary>
        /// Assigns the specified routes.
        /// </summary>
        /// <param name="routes">The routes.</param>
        public static void Assign(RouteCollection routes)
        {
            using (routes.GetReadLock())
            {
                var routeHandler
                    = new RouteHandler<THttpHandler>(
                        ControllerBuilder.Current.GetControllerFactory());

                foreach (var route in routes
                    .OfType<Route>()
                    .Where(r => (r.RouteHandler is MvcRouteHandler)))
                {
                    route.RouteHandler = routeHandler;
                }
            }
        }

        /// <summary>
        /// Returns the HTTP handler by using the specified HTTP context.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <returns>
        /// The HTTP handler.
        /// </returns>
        protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            requestContext.HttpContext
                .SetSessionStateBehavior(
                    this.GetSessionStateBehavior(requestContext));

            return (IHttpHandler)Activator
                                     .CreateInstance(typeof(THttpHandler), requestContext);
        }
    }
}